#pragma once
#include <iostream>
#include <sys/types.h> //mkfifo
#include <sys/stat.h>  //mkfifo
#include <cstdio>      //perror
#include <fcntl.h>     //open
#include <unistd.h>    //read
#include <cstring>     //strlent
#include <string>

#define PATH_NAME "./common"

class named_pipe
{
public:
    named_pipe()
    {
    }
    void Create(const char* str = PATH_NAME)
    {
        // 建立命名管道文件
        int ret = mkfifo(str, 0666);
        if (ret < 0)
        {
            perror("mkfifo");
            exit(1);
        }
    }
    void OpenForRead()
    {
        int fd = open("common", O_RDONLY);
        char buffer[256];
        while (true)
        {
            ssize_t ret = read(fd, buffer, sizeof(buffer));
            if (ret > 0) // 读取到内容
            {
                buffer[ret] = '\0';
                std::cout << buffer << std::endl;
            }
            else if (ret == 0) // 读到文件末尾
            {
                perror("utile file end");
                break;
            }
            else // 读取错误
            {
                perror("read failed\n");
                exit(1);
            }
        }
    }
    void OpenForWrite()
    {
        // 对于写端 , 管道文件和普通文件一样操作
        int fd = open("common", O_WRONLY | O_APPEND | O_TRUNC);
        char buffer[256];
        while (true)
        {
            std::cout << "请输入要发送的内容: ";
            fgets(buffer, 256, stdin);
            int len = strlen(buffer);
            write(fd, buffer, len - 1);
        }
    }
    void Destory()
    {
        // 删除管道文件
        unlink("common");
    }

private:
    std::string _name;
    int _fd;
};
